package com.ican.study2.common.common;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;

import com.ican.study2.common.util.SpringContextUtils;

public class MyHandlerExceptionResolver extends AbstractHandlerExceptionResolver {

    private static final Logger logger = LoggerFactory.getLogger(MyHandlerExceptionResolver.class);

    public MyHandlerExceptionResolver() {
        setOrder(Ordered.LOWEST_PRECEDENCE);
    }

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        if (ex instanceof BusinessException) {
            return handleBusinessException((BusinessException) ex, request, response, handler);
        } else {
            return handleException(ex, request, response, handler);
        }
    }

    protected ModelAndView handleBusinessException(BusinessException e, HttpServletRequest request, HttpServletResponse response, Object handler) {
        String code = e.getCode();
        String msg = e.getMsg();
        if (msg == null && code != null) {
            msg = SpringContextUtils.getContext().getMessage(code, e.getParams(), request.getLocale());
            if (msg == null) {
                msg = code;
            }
        }
        if (msg == null) {
            msg = e.getMessage();
        }
        if (code == null) {
            code = "500";
        }
        logger.error(msg, e);
        Map<String, String> model = new HashMap<String, String>();
        model.put("code", code);
        model.put("msg", msg);
        return new ModelAndView("/common/500", model);
    }

    protected ModelAndView handleException(Exception e, HttpServletRequest request, HttpServletResponse response, Object handler) {
        logger.error(e.getMessage(), e);
        Map<String, String> model = new HashMap<String, String>();
        model.put("code", "000");
        model.put("msg", e.getMessage());
        return new ModelAndView("/common/000", model);
    }
}
